<template>
  <el-dialog :title="title" :visible="visible" width="950px" append-to-body @close="$emit('update:visible',false)">
    选择打印设备：<el-select v-model="printVal" placeholder="请选择" size="small">
                    <el-option
                      v-for="item in printEquips"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
    <el-button size="small" @click="print('true','false')">普通打印</el-button>
    <el-button size="small" @click="print('true','true')">RFID打印</el-button>
    <el-button size="small" @click="print('false','true')">打印预览</el-button>
    <el-button icon="el-icon-download" size="small" @click="downloadPlugin">打印插件</el-button>
    <a style="color: red;margin-left: 10px;font-size: 12px;text-decoration: underline;" @click="downloadPlugin">请点击下载安装并运行打印控件</a>
    <el-divider></el-divider>
    <div id="pcon" v-show="printImg.length">
      <img v-for="img in printImg" :src="img" alt="" style="border: 1px solid #000;margin-bottom: 15px;">
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-width="105px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="打印模板" prop="template">
            <el-select v-model="form.template" placeholder="请选择打印模板" @change="templateChange" style="width: 100%;">
              <el-option
                v-for="dict in templateList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="纸张宽度(mm)" prop="pageW">
            <el-input-number :precision="2" v-model="form.pageW" placeholder="请输入纸张宽度" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="纸张高度(mm)" prop="pageH">
            <el-input-number :precision="2" v-model="form.pageH" placeholder="请输入纸张高度" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="二维码位置(x)" prop="codexy">
            <el-input-number :precision="2" v-model="form.codex" placeholder="请输入资产编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="二维码位置(y)" prop="codexy">
            <el-input-number :precision="2" v-model="form.codey" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-hasPermi="['manage:position:edit']">
          <el-form-item label="二维码大小" prop="codeSize">
            <el-input-number :precision="2" v-model="form.codeSize" placeholder="请输入资产编码"  />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="文本位置x" prop="textX">
            <el-input-number :precision="2" v-model="form.textX" placeholder="请输入资产编码"  />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="文本位置y" prop="textY">
            <el-input-number :precision="2" v-model="form.textY" placeholder="请输入资产编码"  />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-hasPermi="['manage:position:edit']">
          <el-form-item label="文本间隔" prop="textLineheight">
            <el-input-number :precision="2" v-model="form.textLineheight" placeholder="请输入资产编码"  />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="字体大小" prop="fontsize">
            <el-input-number :precision="2" v-model="form.fontsize" placeholder="请输入资产编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12"  v-hasPermi="['manage:position:edit']">
          <el-form-item label="字体宽" prop="typefaceWidth">
            <el-input-number :precision="2" v-model="form.typefaceWidth" placeholder="请输入字体宽" />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-hasPermi="['manage:position:edit']">
          <el-form-item label="字体高" prop="typefaceHeight" >
            <el-input-number :precision="2" v-model="form.typefaceHeight" placeholder="请输入字体高" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="标题位置x" prop="titleX">
            <el-input-number :precision="2" v-model="form.titleX" placeholder="请输入资产编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="标题位置y" prop="titleY">
            <el-input-number :precision="2" v-model="form.titleY" placeholder="请输入资产编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-hasPermi="['manage:position:edit']">
          <el-form-item label="标题大小" prop="titlesize">
            <el-input-number :precision="2" v-model="form.titlesize" placeholder="请输入标题大小" />
          </el-form-item>
        </el-col>
<!--         <el-col :span="12">
          <el-form-item label="字体宽" prop="textW">
            <el-input v-model="form.textW" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="字体高" prop="textH">
            <el-input v-model="form.textH" placeholder="请输入资产编码"/>
          </el-form-item>
        </el-col>-->
      </el-row>
    </el-form>
    <el-divider></el-divider>
  </el-dialog>
</template>

<script>
// import axios from 'axios'
import { getTemplateList, getFieldList } from "@/api/manage/fields";
import {delAsset} from "@/api/manage/asset";
let ws = null
const wslink = function (url, pack, onback) {
  if (ws == null) {
    ws = new WebSocket(url);
    ws.onback = onback;
    ws.onopen = function (evt) {
      ws.send(JSON.stringify(pack))
    };
    ws.onclose = function (evt) {
      ws = null
    };
    ws.onmessage = function (evt) {
      ws.onback(true, eval('(' + evt.data + ')'))
    };
    ws.onerror = function (evt) {
      ws.onback(false, evt)
    }
  } else {
    ws.onback = onback; ws.send(JSON.stringify(pack))
  }
}
export default {
  props: ['visible', 'title', 'assets'],
  data() {
    return {
      printEquips: [],
      fieldSort: [
        {key: 'assetCode', value: '', label: '资产编号'},
        {key: 'assetName', value: '', label: '资产名称'},
        {key: 'brandName', value: '', label: '品牌'},
        {key: 'modelName', value: '', label: '型号'},
        {key: 'deptName', value: '', label: '使用部门'},
      ],
      form: {
        pageW: 70,
        pageH: 40,
        codex: 8,
        codey: 12.5,
        codeSize: 15,
        textX: 25,
        textY: 8,
        textLineheight: 5,
        textW: 50,
        textH: 30,
        fontsize: 8,
        titleX: 28,
        titleY: 4,
        typefaceHeight:5,
        typefaceWidth:5,
        titlesize:10,
        template: undefined,
      },
      rules: {
        template: [{required: true, message: "打印模板不能为空", trigger: "blur"}],
      },
      printVal: null,
      printImg: [],
      templateList: [],
      allFields: [],
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.printImg = []
      }
    }
  },
  mounted() {
    this.init()
    this.getTemplateList()
    this.getFieldList()
  },
  methods: {
    init() {
      this.callBackFunGetPrinter()
    },
    getTemplateList() {
      getTemplateList().then(response => {
        this.templateList = response.data
      })
    },
    getFieldList() {
      getFieldList().then(res => {
        this.allFields = res.data
      })
    },
    // 打印模板变更事件
    templateChange(e) {
      // console.log(e);
      this.templateList.forEach(item => {
        if (item.id === e) {
          let fields = JSON.parse(item.fields)
          let fieldSort = []
          fields.forEach(key => {
            this.allFields.forEach(field => {
              if (field.key === key) fieldSort.push(field)
            })
          })
          this.fieldSort = fieldSort
          let sysPrintPosition = item.sysPrintPosition
          this.form = {
            ...this.form,
            pageW: sysPrintPosition.pageWidth,
            pageH: sysPrintPosition.pageHeight,
            codex: sysPrintPosition.qrCodeX,
            codey: sysPrintPosition.qrCodeY,
            codeSize: sysPrintPosition.qrCodeSize,
            textX: sysPrintPosition.textX,
            textY: sysPrintPosition.textY,
            textLineheight: sysPrintPosition.textInterval,
            titleX: sysPrintPosition.titleX,
            titleY: sysPrintPosition.titleY,
            fontsize: sysPrintPosition.fontsize,
            typefaceHeight: sysPrintPosition.typefaceHeight,
            typefaceWidth: sysPrintPosition.typefaceWidth,
            titlesize: sysPrintPosition.titlesize,
          }
          console.log(this.form);
        }
      })
    },
    // 获取和选择打印机
    callBackFunGetPrinter() {
      let params = {
        command: '_thermal_enum_printer_',
        require: 'usb',
      }
      wslink('ws://127.0.0.1:8008/thermal.ws', params, (success, res) => {
        if (success) {
          console.log(res);
          let data = res
          if (data.code == 0) {
            this.printEquips = data.device
            this.printVal = data.device[0]
          }
        }
      })
    },
    //
    print(isPrint,rfid) {
      let validateFlag = false
      this.$refs["form"].validate(valid => {
        if (!valid) validateFlag = true
      })
      if (validateFlag) return
      // this.assets.forEach(item => {
      //   this.printexec(item, isPrint)
      // })
      if (isPrint === 'false') this.printImg = []
      let assets = JSON.parse(JSON.stringify(this.assets))
      let row = assets.slice(0,1)[0]
      let success = true
      let timer = setInterval(async() => {
        if (!row) {
          console.log('全部打印完成');
          clearInterval(timer)
          return
        }
        if (success) {
          success = false
          if (rfid=== 'true'){
            success = await this.writeEPC(row)
          }
          success = await this.printexec(row, isPrint)
          if (success) {
            assets.splice(0, 1)
            row = assets.slice(0,1)[0]
          } else {
            console.log(JSON.stringify(row))
            clearInterval(timer)
          }
        }
      }, 500)
     let ids=[];
      // 打印的设备id
      assets.forEach((asset)=>{
        ids.push(asset.id)
      });
      addAssetChanges(ids)

    },
    // 打开打印机
    beginWork(port) {
      web_DSOpenPrinter(port, callBackFunOpenPrinter);
      let callBackFunOpenPrinter = (retVal) => {
        if (console) {
          console.log("打开打印机：" + retVal.RtnVal);
        }
        // printOpen = true;打开成功
        // this.assets.forEach(item => {
        //   this.writeEPC(item)
        // })
      }
      setTimeout(() => {
        this.assets.forEach(item => {
          this.writeEPC(item)
        })
      }, 1000)
    },
    // 写入epc
    writeEPC(row) {
      return new Promise((resolve, reject) => {
        let epc = row.rfidCode;
        console.log("状态正常，准备写入" + epc);
        let params = {
          command: '_thermal_cmd_engine_controler_',
          device: this.printVal,
          func: 'rfid_dynmic_write_epc',
          data: epc,
        }
        wslink('ws://127.0.0.1:8008/thermal.ws', params, (success, res) => {
          if (success) {
            console.log(res);
            let data = res
            if (data.code == 0) {
              resolve(true)
            } else {
              reject(false)
            }
          }
        })
      })
    },
    // 写入文本和二维码
    printexec(row, isPrint) {
      return new Promise((resolve, reject) => {
        let params = {
          command: '_thermal_zpl_draw_print_',
          device : this.printVal,
          printdirectly: isPrint,
          measurement_mode: 'mm',
          canvas_size: { "width": parseFloat(this.form.pageW), "height": parseFloat(this.form.pageH) },
          is_label: 'false',
          print  : [],
          get_base64_img: 'true'
        }
        //设置字体（需要系统存在的字体）
        params.print.push({ func: 'PDSetFont', szFontName: '宋体', fSize: parseFloat(this.form.fontsize) })

        //设置文本信息
        params.print.push({ func: 'PDSetTextDecorate', iIsLandScape: 1, iIsReverseSequence: 0, iIsAutoLineFeed: 0, iIsLayDown: 0 })

        //绘制标题
        // params.print.push({ func: 'PDDrawTextW', iX: parseFloat(this.form.titleX), iY: parseFloat(this.form.titleY-5), iWidth: parseFloat(this.form.textW), iHeight: parseFloat(this.form.textH), wszText: row.companyName||' ' })
        params.print.push({ func: 'PDDrawImage',
          iX: parseFloat(this.form.titleX),
          iY: parseFloat(this.form.titleY),
          iWidth: parseFloat(Number(this.form.titlesize)*3.7),
          iHeight: parseFloat(Number(this.form.titlesize)/2.7),
          szImageFile: this.textBecomeImg(row.companyName, 300, '#000') })


          //绘制文字
        // params.print.push({ func: 'PDDrawTextW', iX: 16, iY: 15, iWidth: 50, iHeight: 30, wszText: '姓 名: 王𪚥军' })
        this.fieldSort.forEach((field,i) => {
          let text = field.label+'：'+(row[field.key]||'')
          params.print.push({ func: 'PDDrawTextW', iX: parseFloat(this.form.textX), iY: parseFloat(parseFloat(this.form.textY)+(parseFloat(this.form.textLineheight)*i)), iWidth: parseFloat(this.form.textW), iHeight: parseFloat(this.form.textH), wszText: text })
        })

        //绘制二维码
        params.print.push({ func: 'PDDrawQRCode', iX: parseFloat(this.form.codex), iY: parseFloat(this.form.codey), iWidth: parseFloat(this.form.codeSize), iHeight: parseFloat(this.form.codeSize), szData: row.rfidCode})

        wslink('ws://127.0.0.1:8008/thermal.ws', params, (success, res) => {
          if (success) {
            console.log(res);
            let data = res
            if (data.code == 0) {
              if (isPrint === 'false') this.printImg = this.printImg.concat(data.image_base64)
              resolve(true)
            } else {
              reject(false)
            }
          }
        })
      })
    },
    // 写二维码
    printQrCode(XposQrCode,
                YposQrCode,
                sizeQrCode,
                textQrCode,
                byDarknessQrCode,//打印深度
                ErrLevelQrCode//容错级别)
    ) {
      web_DSZPLPrintQrCodeExA(0, parseInt(byDarknessQrCode), parseFloat(XposQrCode), parseFloat(YposQrCode), parseFloat(sizeQrCode), parseInt(ErrLevelQrCode), textQrCode);
    },
    // 写文本
    printText(byDarkness, dXPos, dYpos, widthSizeFont,heightSizeFont,content,font) {
      web_DSZPLPrintTextEx(0, font, false, false, parseFloat(byDarkness), parseFloat(dXPos), parseFloat(dYpos), parseFloat(heightSizeFont), parseFloat(widthSizeFont), content);
    },
    // 转文本图片
    textBecomeImg(text,fontsize,fontcolor) {
      var canvas = document.createElement('canvas');
      //小于32字加1  小于60字加2  小于80字加4    小于100字加6
      var $buHeight = 0;
      if(fontsize <= 32){ $buHeight = 1; }
      else if(fontsize > 32 && fontsize <= 60 ){ $buHeight = 2;}
      else if(fontsize > 60 && fontsize <= 80 ){ $buHeight = 4;}
      else if(fontsize > 80 && fontsize <= 100 ){ $buHeight = 6;}
      else if(fontsize > 100 ){ $buHeight = 10;}
      //对于g j 等有时会有遮挡，这里增加一些高度
      canvas.height=fontsize + $buHeight ;
      var context = canvas.getContext('2d');
      // 擦除(0,0)位置大小为200x200的矩形，擦除的意思是把该区域变为透明
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.fillStyle = fontcolor;
      context.font=fontsize+"px Arial";
      //top（顶部对齐） hanging（悬挂） middle（中间对齐） bottom（底部对齐） alphabetic是默认值
      context.textBaseline = 'middle';
      context.fillText(text,0,fontsize/2)

      //如果在这里直接设置宽度和高度会造成内容丢失 , 暂时未找到原因 , 可以用以下方案临时解决
      //canvas.width = context.measureText(text).width;

      canvas.width = context.measureText(text).width;
      context.fillStyle = fontcolor;
      context.font='500 '+fontsize+"px FANGSONG";
      context.textBaseline = 'middle';
      context.fillText(text,0,fontsize/2)

      var dataUrl = canvas.toDataURL('image/png');//注意这里背景透明的话，需要使用png
      return dataUrl;
    },
    /** 下载插件 */
    downloadPlugin() {
      const x = new XMLHttpRequest()
      x.open('GET', 'https://qmappbg.cjform.cn/prod-api/profile/得实网页打印助手.exe', true)
      x.responseType = 'blob'
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      x.onload = function(e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a')
        a.href = url
        a.download = '得实网页打印助手.exe'
        a.click()
        loading.close()
      }
      x.send()
    }
  },
};
import {addAssetChanges} from "@/api/manage/assetChange";
</script>



<style lang="scss" scoped>
#pcon {
  height: 470px;
  overflow-y: scroll;
}
</style>
